<?php

namespace Addons\MarkDoc\Model;

/**
 * MarkDoc模型
 */
class MarkDoc{

    public function __construct($path){
        $this->root = $path;
    }

    public function getList(){
        $root = $this->root.'/docs';
        if(S('MarkDoc_list') && filemtime($root) < time()){
            $list = S('MarkDoc_list');
        }else{
            $list = $this->getTree($root);
            S('MarkDoc_list', $list);
        }
        return $list;
    }

    //获取文档列表
    private function getTree($path, $type = 'dir'){
        static $tree = array();
    }

    function homepage_url($tree) {
        // Check for homepage
        if (isset($tree['index'])) {
            return '/';
        } else {
            return docs_url($tree, false);
        }
    }

    function url_params() {
        $url = rawurldecode(get_uri());
        $url = ltrim($url, '/Index/single/name/MarkDoc');
        $params = explode('/', trim($url, '/'));
        return $params;
    }

    function load_page($tree, $url_params , $default_title = '') {
        if (count($url_params) > 0) {
            $branch = $this->find_branch($tree, $url_params);
        } else {
            $branch = current($tree);
        }

        $page = array();

        if (isset($branch['type']) && $branch['type'] == 'file') {
            $html = '';
            if ($branch['name'] !== 'index') {

                $page['title'] = $branch['title'];
                $page['modified'] = filemtime($branch['path']);

            }else{
                $page['title'] = $default_title;
            }
            require_once($this->root.'/libs/markdown_extended.php');
            $html .= MarkdownExtended(file_get_contents($branch['path']));

            $page['html'] = $html;

        } else {

            $page['title'] = "Oh no";
            $page['html'] = "<h3>Oh No. 页面不存在</h3>";

        }

        return $page;
    }

    function find_branch($tree, $url_params) {
        foreach($url_params as $peice) {

            // Support for cyrillic URLs
            $peice = urldecode($peice);

            // Check for homepage
            if (empty($peice)) {
                $peice = 'index';
            }

            if (isset($tree[$peice])) {
                if ($tree[$peice]['type'] == 'folder') {
                    $tree = $tree[$peice]['tree'];
                } else {
                    $tree = $tree[$peice];
                }
            } else {
                return false;
            }
        }

        return $tree;
    }
}
